import activist.Event
import activist.Group
import activist.Person
import activist.Place
import activist.Media
import activist.Article
from activist.Users import Users

import time

CLASS_TO_URL = {
    activist.Event.Event: 'event',
    activist.Group.Group: 'group',
    activist.Person.Person: 'person',
    activist.Place.Place: 'place',
    activist.Media.Media: 'media',
    activist.Article.Article: 'article'
    }
# not defined in Nevow anywhere I can find :(
SESSION_STARTED = '__session_just_started__=1'

def makeURL(uri, obj):
    if isinstance(obj,activist.Person.Person) and obj.username() and Users.has_key(obj.username()):
        return makeRelative(uri, '/user/' + str(obj.username()))
    try:
        typ = CLASS_TO_URL[obj.__class__]
    except:
        return makeRelative(uri, '/object/%s'%(obj.id(),))
    return makeRelative(uri, '/%s/%s' % (typ,obj.id()))

def makeRelative(uri,rest):
    if uri is None:
        return rest
    if rest[0] != '/':
        return rest
    
    if uri.find('?') >= 0:
        uri,query = uri.split('?',1)
    if uri[-1] == '/':
        uri = uri[:-1]
    dots = '../' * uri.count('/')
    query = None
    if query:
        if query.find(SESSION_STARTED) == 0:
            query = query[len(SESSION_STARTED):]
        if len(query):
            query = '?' + query
    else:
        query = ''
    return  dots + rest[1:] + query

def makeTimeURLFromEvent(uri, obj):
    tm = obj.info().whenRaw()
    close = tm.closestTimeTo(time.time())
    return makeRelative(uri, '/event/time/%04d/%02d' % (close.tm_year, close.tm_mon))

def addGetVariable(uri,var,value):
    value = str(value)
    if '?' in uri:
        rtn,rest = uri.split('?',2)
        get = ''
        for uncoded in rest.split('&'):
            (a,b) = uncoded.split('=')
            if a == var:
                get = get + var + '=' + value + '&'
            else:
                get = get + uncoded + '&'
        return rtn + '?' + get[:-1]
    return uri + '?' + var + '=' + value
